<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2017/12/18
 * Time: 上午9:20
 */


function testpost() {
    $data = array(
        'uid' => '01234',
        'content' => '这是内容'
    );
    $data = http_build_query($data);
    $opts = array(
        "http" => array(
            "method" => "POST",
            "header" => "Host:localhost\r\n".
            "Content-type:application/x-wwww-form-urlencoded\r\n".
            "Content-length:".strlen($data)."\r\n",
            "content" => $data
        )
    );
    $context = stream_context_create($opts);
    $content = file_get_contents("http://localhost/index.php",false,$context);
    echo $content;
    $content = fopen("http://localhost/index.php","r",false,$context);
    echo $content;
}

function socket() {
    $data = array(
        'uid' => '01234',
        'content' => '这是内容'
    );
    $data = http_build_query($data);
    $fp = fsockopen("localhost",80,$errno,$errnoStr,5);
    $request = "POST http://locahost/index.php HTTP/1.1\r\n";
    $request.="Host:localhost\r\n";
    $request.="Content-type:application/x-wwww-form-urlencoded\r\n";
    $request.= "Content-length:".strlen($data)."\r\n\r\n";
    $request.=$data;
    fwrite($fp,$request);
    while(!feof($fp)){
        echo fgets($fp);
    };
    fclose($fp);
}

//下载文件
function httpcopy($url, $file="", $timeout=60) {
    $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
    $dir = pathinfo($file,PATHINFO_DIRNAME);
    !is_dir($dir) && @mkdir($dir,0755,true);
    $url = str_replace(" ","%20",$url);

    if(function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $temp = curl_exec($ch);
        if(@file_put_contents($file, $temp) && !curl_error($ch)) {
            return $file;
        } else {
            return false;
        }
    } else {
        $opts = array(
            "http"=>array(
                "method"=>"GET",
                "header"=>"",
                "timeout"=>$timeout)
        );
        $context = stream_context_create($opts);
        if(@copy($url, $file, $context)) {
            return $file;
        } else {
            return false;
        }
    }
}

//---

$message = "hello";
//使用use从父作用域集成变量
$closure = function ($name) use ($message) {
    echo $message ." ".$name;
};
$message = "11111";//如果想让message可以改变,用 use(&$message)

$closure('world');



